package com.zhida.jiyangcenter.modle

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import com.amap.api.location.AMapLocationClient
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.StoreExaminationListEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.getLocation
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_healthy_test.*


@TitleBar(false)
@ContentLayout(R.layout.activity_healthy_test)
class HealthyTestStroeActivity : BaseActivity() {
    var page = 1
    val adapter = Adapter()
    var city = ""
    var latitude = 0.0
    var longitude = 0.0
    private lateinit var loadService: LoadService<*>


    //声明AMapLocationClient类对象
    private lateinit var locationClient: AMapLocationClient
    override fun initConfig(savedInstanceState: Bundle?) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        view_status_bar.updateLayoutParams<ConstraintLayout.LayoutParams> {
            height = getStatusBarHeight()
        }
        loadService = LoadUtils.getDefault().register(rv_store) {
            page = 1
            getData()
        }
        tv_commit.gone()
        rv_store.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_store.adapter = adapter
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, rv_store)
        rv_store.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context)
                .sizeResId(R.dimen.marginContentSmall).colorResId(R.color.colorBack).build()
        )
//        adapter.setOnItemClickListener { _, view, position ->
//            startActivity<PhysicalExaminationActivity> {
//                putExtra("uuid", adapter.data[position].uuid)
//                putExtra("city", city)
//            }
//        }
        locationClient = getLocation(context) {
            city = it.city
            latitude = it.latitude
            longitude = it.longitude
            getData()
        }
        iv_store_search.setOnClickListener {
            ll_store_search.visible()
            iv_store_search.gone()
        }
        edit_text.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                page = 1
                search = edit_text.text.toString()
                iv_store_search.visible()
                ll_store_search.gone()
                val manager: InputMethodManager =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(
                    v.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
                getData()
            }
            false
        }
    }

    var search = ""
    override fun onResume() {
        super.onResume()
        getData()

    }

    override fun onPause() {
        locationClient.stopLocation()
        super.onPause()
    }

    override fun onDestroy() {
        locationClient.onDestroy()
        super.onDestroy()
    }

    private fun getData() {
        showTipLoading()
        lifecycleScope.request({
            if (intent.getStringExtra("type") == "1") {
                APIShop.service()
                    .storeHealthList(
                        intent.getStringExtra("uuid"),
                        longitude,
                        latitude,
                        page,
                        search
                    )
            } else {
                APIShop.service()
                    .storeExaminationList(
                        intent.getStringExtra("uuid"),
                        longitude,
                        latitude,
                        page,
                        search
                    )
            }
        }, object : BaseAPI<StoreExaminationListEntity>() {
            override fun onSuccess(t: StoreExaminationListEntity?, state: Int, msg: String) {
                hideTipLoading()
                if (t != null && !t.serve.isNullOrEmpty()) {
                    if (page <= 1) {
                        adapter.setNewData(t.serve)
                        loadService.showSuccess()
                        if (t.serve.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        }
                    } else {
                        adapter.addData(t.serve)
                        if (t.serve.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        } else adapter.loadMoreComplete()
                    }
                } else onError(APIException(APIException.Type.EMPTY))
            }

            override fun onError(e: APIException) {
                hideTipLoading()
                if (page <= 1) when (e.type) {
                    APIException.Type.EMPTY -> loadService.showCallback(
                        EmptyCallback::class,
                        "暂无服务"
                    )
                    APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                    else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                } else when (e.type) {
                    APIException.Type.EMPTY -> {
                        adapter.loadMoreFail()
                    }
                    else -> adapter.loadMoreFail()
                }
            }

        })
    }

    class Adapter :
        BaseQuickAdapter<StoreExaminationListEntity.Serve, BaseViewHolder>(R.layout.item_healthy_test) {
        override fun convert(helper: BaseViewHolder, item: StoreExaminationListEntity.Serve?) {
            glideImage(helper.getView(R.id.civ_fragment_main_healthy), item?.picture ?: "")
            helper.setText(R.id.tv_healthy_title, item?.name)
                .setText(R.id.tv_healthy_money, "￥" + item?.price)
                .setText(R.id.tv_healthy_name, item?.store_name)
                .setText(R.id.tv_healthy_address, item?.distance + "km")
            val rv_store_tab = helper.getView<RecyclerView>(R.id.rv_healthy_tab)
            rv_store_tab.layoutManager =
                object : LinearLayoutManager(mContext, HORIZONTAL, false) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }
                }
            rv_store_tab.adapter = TabAdapter().apply {
                setNewData(item?.subtitle?.split(" "))
            }
            rv_store_tab.addItemDecoration(
                VerticalDividerItemDecoration.Builder(mContext)
                    .sizeResId(R.dimen.d4).colorResId(R.color.white).build()
            )
            val rv_store_project = helper.getView<RecyclerView>(R.id.rv_healthy_project)
            rv_store_project.layoutManager = object : LinearLayoutManager(mContext) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rv_store_project.adapter = ProjectAdapter().apply {
                setNewData(item?.description?.split("，"))
            }
            rv_store_project.addItemDecoration(
                HorizontalDividerItemDecoration.Builder(mContext)
                    .sizeResId(R.dimen.d4).colorResId(R.color.white).build()
            )


        }

        class TabAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_fragment_main_store_tab) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                helper.setText(R.id.tv_tab, item)
                    .setBackgroundRes(R.id.tv_tab, R.drawable.bg_fill_f1efef100)
                    .setTextColor(R.id.tv_tab, mContext.resColor(R.color.textGray))
            }

        }

        class ProjectAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_fragment_main_store_tab) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                helper.setText(R.id.tv_tab, item)
                    .setBackgroundRes(R.id.tv_tab, R.drawable.bg_empty_blue8)
                    .setTextColor(R.id.tv_tab, mContext.resColor(R.color.textColor))
            }

        }
    }
}